#!/usr/bin/python

import os
import sys
from datetime import datetime

log = False
log = True

logdir = os.path.expanduser("~/.dflv")
if not os.path.exists(logdir):
    os.mkdir(logdir)
dfname = datetime.now().isoformat()

log and os.makedirs(os.path.sep.join([logdir,dfname]))
logfile = os.path.sep.join([logdir,dfname,'log'])
wgetlogfile = os.path.sep.join([logdir,dfname,'wgetlog'])

log = log and open(logfile,'w')

try:
    socks_server = '192.168.1.2:31777'
    
    ua = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.16) Gecko/20110323 Ubuntu/10.10 (maverick) Firefox/3.6.16"

    log and log.write(' '.join(sys.argv) + '\n')
    fname = 'flashgot.down'
    referer = ''
    if len(sys.argv) == 6:
        _, folder, cookiefile, url, referer, fname = sys.argv
    elif len(sys.argv) == 5:
        _, folder, cookiefile, url, referer = sys.argv
    elif len(sys.argv) == 4:
        _, folder, cookiefile, url = sys.argv
    i = 1

    con=0
    if os.path.exists(os.path.join(folder,tfname)):
        con=os.stat(os.path.join(folder,tfname)).st_size
    cmd = '''xterm -e 'curl --retry 100000 '''
    if socks_server:
        cmd = cmd + ''' --socks5 "%s" ''' % socks_server
    if con:
        cmd = cmd + ''' -C %d ''' % con
    cmd = cmd + ''' -o "%s" --user-agent "%s" ''' % (os.path.join(folder,fname), ua)
    if referer:
        cmd = cmd + ''' --referer "%s" ''' % referer
    cmd = cmd + ''' --cookie "%s" "%s";read -n 1 -s' ''' % (cookiefile, url)
    log and log.write(cmd + '\n')

    os.system(cmd)
except Exception,e:
    log and log.write(str(e) + '\n')



